package com.tarena.util.datasource;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBConnection {
	private static String url;
	private static String user;
	private static String password;
	static {
		Properties properties = new Properties();
		try {
			InputStream in = new FileInputStream("src/db.properties");
			try {
				properties.load(in);
				url = properties.getProperty("url");
				user = properties.getProperty("user");
				password = properties.getProperty("password");
				Class.forName(properties.getProperty("driver"));
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("注册驱动有误");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("文件未找到");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("配置文件有误");
		}

	}

	public static Connection getConnection() throws Exception {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("连接失败");
		}
		return conn;
	}

	public static void close(ResultSet rs, Statement stat, Connection conn)
			throws Exception {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stat != null) {
				stat.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("关闭失败");
		}
	}

	public static void close(Statement stat, Connection conn) throws Exception {
		try {
			if (stat != null) {
				stat.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("关闭失败");
		}
	}
	public static void main(String[] args) throws Exception{
		System.out.println(DBConnection.getConnection());
	}
}
